package client.comm.baoding.fragment

import android.app.DownloadManager
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.view.ContextMenu
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.lifecycle.Observer
import client.comm.baoding.R
import client.comm.baoding.databinding.FragmentTabzbBinding
import client.comm.baoding.ui.vm.MainViewModel
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.utils.ImageExt
import client.comm.commlib.utils.ImageExt.saveToAlbum
import client.comm.commlib.utils.Util
import client.comm.commlib.widget.EmptyLayout

class TabZbFragment : BaseFragment<FragmentTabzbBinding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_tabzb
    }

    override fun initViewModel(): MainViewModel = createViewModel()

    var title: String? = ""
    var url: String? = ""

    override fun initWidget() {
        binding.statusBar.post {
            val h = Util.getStatusBarHeight(requireContext())
            val p = binding.statusBar.layoutParams
            p.height = h
            binding.statusBar.layoutParams = p
            Util.setBg(resources!!.getColor(client.comm.commlib.R.color.white), requireActivity().window)
            val controller = ViewCompat.getWindowInsetsController(binding.root)
            controller?.isAppearanceLightStatusBars = true
        }
        binding.event = this

    }

    override fun initData() {
        super.initData()
        viewModel.userInfo()
//        url = "https://wx.vzan.com/live/channelpage-255634"
        title = ""
        binding.title = (title)

        val mWebSettings = binding.wvShow.settings
        mWebSettings.setJavaScriptEnabled(true)
        mWebSettings.setBuiltInZoomControls(false)
        mWebSettings.setLightTouchEnabled(true)
        mWebSettings.setSupportZoom(false)

        mWebSettings.javaScriptCanOpenWindowsAutomatically = true
        mWebSettings.cacheMode = WebSettings.LOAD_NO_CACHE;

        //存储页面DOM结构
        mWebSettings.loadWithOverviewMode = true
        mWebSettings.domStorageEnabled = true
        mWebSettings.blockNetworkImage = false
        mWebSettings.useWideViewPort = true
        binding.wvShow.isHapticFeedbackEnabled = false

        registerForContextMenu(binding.wvShow)

        // 特别注意：5.1以上默认禁止了https和http混用，以下方式是开启 允许其加载混合网络协议内容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        viewModel.callUser.observe(this, Observer {
            it?.let {
                if (it.isSuccess) {
                    it.data?.zb_url?.let {
                        binding.wvShow.loadUrl(it)
                    }
                }
            }
        })
        binding.wvShow.setWebViewClient(object : WebViewClient() {

            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, error: SslError?) {
                //证书信任
                handler.proceed() //表示等待证书响应
                // handler.cancel();      //表示挂起连接，为默认方式
                // handler.handleMessage(null);    //可做其他处理
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
                url?.let {
                    view.loadUrl(url!!)
                }
                return true
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                binding.emptyLayout.visibility = View.VISIBLE
            }

//            @RequiresApi(Build.VERSION_CODES.KITKAT)
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                binding.emptyLayout.visibility = View.GONE
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR

            }
        })
    }

    @ExperimentalStdlibApi
    override fun onCreateContextMenu(
        contextMenu: ContextMenu,
        view: View,
        contextMenuInfo: ContextMenu.ContextMenuInfo?
    ) {
        super.onCreateContextMenu(contextMenu, view, contextMenuInfo)

        val webViewHitTestResult: WebView.HitTestResult = binding.wvShow.getHitTestResult()
        if (webViewHitTestResult.type === WebView.HitTestResult.IMAGE_TYPE ||
            webViewHitTestResult.type === WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE
        ) {
            contextMenu.setHeaderTitle("网页中下载图片")
            contextMenu.add(0, 1, 0, "点击保存")
                .setOnMenuItemClickListener {
                    val DownloadImageURL = webViewHitTestResult.extra

                    if (URLUtil.isDataUrl(DownloadImageURL)) {
                        var bitmap = ImageExt.convertBase64ToPic(DownloadImageURL!!)
                        var result = false
                        bitmap?.let {
                            val uri = it.saveToAlbum(requireContext(), fileName = "${System.currentTimeMillis()}.png")
                            result = uri != null
                        }
                        if (result) {
                            Toast.makeText(requireContext(), "下载成功", Toast.LENGTH_LONG).show()
                        } else {
                            Toast.makeText(requireContext(), "下载失败", Toast.LENGTH_LONG).show()
                        }
                    } else if (URLUtil.isValidUrl(DownloadImageURL)) {
                        val request: DownloadManager.Request = DownloadManager.Request(Uri.parse(DownloadImageURL))
                        request.allowScanningByMediaScanner()
                        //设置图片的保存路径
                        request.setDestinationInExternalFilesDir(requireContext(), "/img", "/a.png")
                        val downloadManager: DownloadManager =
                            requireContext().getSystemService(AppCompatActivity.DOWNLOAD_SERVICE) as DownloadManager
                        downloadManager.enqueue(request)
                        Toast.makeText(requireContext(), "下载成功", Toast.LENGTH_LONG).show()
                    } else {
                        Toast.makeText(requireContext(), "下载失败", Toast.LENGTH_LONG).show()
                    }
                    false
                }
        }
    }


    fun onKeyDownChild(keyCode: Int, event: KeyEvent?) {

    }

    //    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//
//        if (keyCode == KeyEvent.KEYCODE_BACK && binding.wvShow.canGoBack()) {
//            binding.wvShow.goBack() //返回上个页面
//            return true
//        }
////        else{
////            onBackPressed();
////        }
//
//        return super.onKeyDown(keyCode, event) //退出H5界面
//    }
//
//
//    // 千万注意这里可没有重写父类的  super.onBackPressed(); ，如果有这个你的设置是无效的，所以记得删除！（至于是否可以将这行代码移动到末尾处，君请亲测）
//    override fun onBackPressed() {
//        if (binding.wvShow.canGoBack()) {
//            binding.wvShow.goBack()
//        } else {
//            finish()
//            //onBackPressed();
//        }
//    }
//
    override fun onDestroy() {
        binding.wvShow.destroy()
        super.onDestroy()
    }


}